const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const fs = require('fs');
const helper = require('../../util/helper');
const path = require('path');
const crypto = require('crypto');

exports.save = async(ctx) => {
    try {
        if (!ctx.req.body['path']) {
            ctx.req.body['path'] = '';
        }
        if (!ctx.req.file) {
            ctx.body = {
                result: 201,
                message: "参数错误"
            };
            return;
        }
        let sourceFile = ctx.req.file.path;
        let destPath = path.join(ctx.req.file.destination, ctx.req.body['path']);
        if (!helper.mkdirsSyncEx(destPath)) {
            ctx.body = {
                result: 202,
                message: "路径错误"
            };
            return;
        }
        destPath = path.join(destPath,ctx.req.file.filename);//,ctx.req.file.filename
        await new Promise((resolve, reject) => {
            let start = new Date().getTime();
            let md5sum = crypto.createHash('md5');
            let stream = fs.createReadStream(sourceFile);
            stream.on('data', function(chunk) {
                md5sum.update(chunk);
            });
            stream.on('end', function() {
                let str = md5sum.digest('hex').toUpperCase();
                resolve(str);
            });
        }).then((str) => {
            return new Promise((resolve, reject) => {
                try {
                    mysql.query('select * from file where md5_hash = ? and path = ? order by id ',
                        [str,path.relative(__publicPath,path.dirname(destPath))],function (err,rows) {
                        if (err){
                            ctx.body = {
                                result: 203,
                                message: "失败" + err.toString()
                            };
                            reject(ctx);
                        }else{
                            if (rows.length > 0){
                                let file_path = path.join(__publicPath ,rows[0].path,rows[0].filename);
                                fs.stat(file_path, function (err, stats) {
                                    if (err) {
                                        //文件不存在 数据库删除该数据
                                        mysql.query('delete from file where id = ? ',rows[0].id,function () {});
                                        resolve(str);
                                    }else{
                                        //文件存在
                                        fs.unlink(sourceFile,function () {});
                                        ctx.body = {
                                            result: 200,
                                            url:path.join(rows[0].path , rows[0].filename),
                                            message: "成功"
                                        };
                                        reject(ctx);
                                    }
                                });
                            } else{
                                resolve(str);
                            }
                        }
                    })
                }catch (e) {
                    ctx.body = {
                        result: 205,
                        message: "错误" + e.toString()
                    };
                    reject(ctx);
                }
            });
        }).then((str) => {
            return new Promise((resolve, reject) => {
                fs.rename(sourceFile, destPath, function (err) {
                    if (err) {
                        ctx.body = {
                            result: 203,
                            message: "失败" + err.toString()
                        };
                        reject(ctx);
                    }else{
                        fs.stat(destPath, function (err, stats) {
                            if (err) {
                                ctx.body = {
                                    result: 204,
                                    message: "失败" + err.toString()
                                };
                                reject(info);
                            }else{
                                resolve({str,destPath});
                            }
                        });
                    }
                });
            });
        }).then((json) => {
            return new Promise((resolve, reject) => {
                try {
                    let newFile = {
                        filename:path.basename(json.destPath),
                        path:path.relative(__publicPath,path.dirname(json.destPath)),
                        md5_hash:json.str,
                        create_user_id:ctx.user.id,
                        create_time:moment().format('YYYY-MM-DD HH:mm:ss')
                    }
                    mysql.query('INSERT INTO file SET ? ',newFile,function (err,info) {
                        if (err || info.affectedRows === 0){
                            ctx.body = {
                                result: 204,
                                message: "失败" + err.toString()
                            };
                            resolve(ctx);
                        } else{
                            ctx.body = {
                                result: 200,
                                url: path.join(newFile.path , newFile.filename),
                                message: "成功"
                            };
                            resolve(ctx);
                        }
                    })
                }catch (e) {
                    ctx.body = {
                        result: 205,
                        message: "错误" + e.toString()
                    };
                    reject(ctx);
                }

            });
        }).catch( (ctx) => {
            return ctx;
        })
    } catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
};